/**
 * MasicInput
 * <p/>
 * User: joakimd
 * Date: 2013-03-11
 * Time: 11:36
 */
package org.dru.masic {
import flash.events.Event;

public final class MasicInput extends MasicPort {
    private var _sources: Vector.<MasicOutput>;
    private var _leased: Boolean;

    public function MasicInput(parent: MasicComponent, name: String, stereo: Boolean) {
        super(parent, name, stereo);
        _sources = new Vector.<MasicOutput>();
        _leased = false;
    }

    internal function get sources(): Vector.<MasicOutput> {
        return _sources;
    }

    public function get numSources(): int {
        return sources.length;
    }

    public function getSourceAt(index: int): MasicOutput {
        return sources[index];
    }

    public function getSourceIndex(source: MasicOutput): int {
        return sources.indexOf(source);
    }

    public function addSource(source: MasicOutput): void {
        if (getSourceIndex(source) == -1) {
            sources.push(source);
            source.addTarget(this);
            update();
            dispatchEvent(new Event(Event.CHANGE));
        }
    }

    public function removeSource(source: MasicOutput): void {
        const index: int = getSourceIndex(source);
        if (index != -1) {
            removeSourceAt(index);
        }
    }

    public function removeAllSources(): void {
        for (var index: int = numSources; --index >= 0;) {
            removeSourceAt(index);
        }
    }

    private function removeSourceAt(index: int): void {
        const source: MasicOutput = sources.splice(index, 1)[0];
        source.removeTarget(this);
        update();
        dispatchEvent(new Event(Event.CHANGE));
    }

    public function get leased(): Boolean {
        return _leased;
    }

    private function update(): void {
        if (_leased) {
            allocate();
            _leased = false;
        }
        else if (numSources == 1) {
            const source: MasicOutput = getSourceAt(0);
            if (MasicUtils.getPortMixCode(this, source) != 2) {
                setLeft(source.left);
                setRight(stereo ? (source.stereo ? source.right : source.left) : null);
                _leased = true;
            }
        }
    }
}
}
